import React, {Suspense} from "react";
import { BrowserRouter as Router, Routes, Route, useLocation, useParams, useSearchParams, useNavigate, Navigate } from 'react-router-dom';
import { Mask,DotLoading   } from 'antd-mobile'
import routes from "./routes";

const isCheckLoginList = [
    '/personal',
    '/store',
    '/updateInfo'
]
/* 创建图标对象 */
const createIconNode = (iconName) => {
    return React.createElement(iconName);
}

/* 手动将常用的路由方法绑定到组件的props属性上面，以后使用就不需要 import 导入了 */

// @1 修改标题 @2 登录态校验
const Element = props => {
    let { component: Component, path, meta } = props;
    let {title = '知乎日报APP'} = meta || {};
    let location = useLocation();
    let params = useParams();
    let [sup] = useSearchParams();
    let navigate = useNavigate();
    document.title = title; //依据当前路由设置的标题，修改页面标题

    if(isCheckLoginList.includes(path)) {
        const token = window.localStorage.getItem('tk');
        if(!token) {
            const to = `/login?to=${path.slice(1)}`;
            return <Navigate to={to} replace />
        }
    }

    return <Component location={location} params={params} sup={sup} navigate={navigate} path={path} meta={meta} />
}

/* 依据routes路由表，动态创建 Route 组件 */
const createRoute = (routes) => {
    return routes && routes.map(route => {
        return <Route key={route.name} path={route.path} element={<Element {...route} />} />
    });
}

/* 构建路由 */
const RouterView = () => {
    return (
        // 懒加载路由
        <Suspense fallback={
            <Mask visible={true} opacity='thin'>
              <div className="flex-loading-box">
                <div><DotLoading  color='primary' /></div>
                <p>加载中 ...</p>
              </div>
            </Mask>}
            >
            <Router>
                <Routes>
                    {/* 这里不能使用组件模式 , 因为<Routers> 下只能嵌套 <Route/>组件 */}
                    {createRoute(routes)}
                </Routes>
            </Router>
        </Suspense>
    )
}

export default RouterView;